from flask import Flask
from flask import render_template, request
import sqlite3
import datetime
import json

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template('index.html')


@app.route('/admin')
def admin():
    return render_template('admin.html')


@app.route('/createdb', methods=['GET'])
def createdb():
    conn = sqlite3.connect('db.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE value
           (
           value           TEXT,
           date            TEXT,
           time            TEXT
           )
           ''')
    conn.commit()

    return '数据库创建成功'


@app.route('/submit', methods=['GET'])
def submit():
    value = request.args.get('v')
    conn = sqlite3.connect('db.db')
    c = conn.cursor()
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    time = datetime.datetime.now().strftime('%H:%M:%S')
    print(date)
    c.execute("INSERT INTO value (value,date,time) VALUES ('%s', '%s','%s')" % (value, date, time))
    conn.commit()
    return value


@app.route('/search', methods=['GET'])
def search():
    v = request.args.get('data')
    conn = sqlite3.connect('db.db')
    c = conn.cursor()
    c.execute("SELECT value,date,time from value where date = '%s'" % v)

    data = []
    for row in c:
        print(str(row))
        value = row[0]
        date = row[1]
        time = row[2]
        data.append({"value": row[0], "date": row[1], "time": row[2]})
    return str(data).replace("'", '"')


app.run(debug=True, threaded=True, port=81)
